<template>
    <div class="wrapper">
        <scroller class="container" :style="scrollerStyle">
            <refresh v-show="false" :style="refreshStyle" class="refresh" @refresh="onrefresh()" @pullingdown="onpullingdown" :display="refreshing ? 'show' : 'hide'">
                    <loading-indicator class="indicator"></loading-indicator>
            </refresh>
            <div class="list">
                <div class="policyCell"  v-for="(item,index) in upkeepCentList" :key="index">
                    <wxc-cell @wxcCellClicked="checkButton(index)" :has-arrow="true" :title="(index+1)+'.'+item.content">
                    </wxc-cell>

                    <wxc-cell @wxcCellClicked="wxcCellClicked"
                            :has-margin="true" :has-bottom-border="false" :title="item.result">
                        <image v-if="item.result ==='正常'" src="bmlocal://assets/confirm-right.png" class="image" slot="label"></image>
                        <image v-if="item.result ==='需修理'" src="bmlocal://assets/confirm-repair.png" class="image" slot="label"></image>
                        <image v-if="item.result ==='无此项'" src="bmlocal://assets/confirm-noItem.png" class="image" slot="label"></image>
                        <image v-if="item.mustPhotos" src="bmlocal://assets/confirm-photo.png" class="image" slot="value"></image>
                    </wxc-cell>
                </div>
                <text class='text-no' v-if="upkeepCentList.length<=0" >暂无数据</text>
                <div class="div-button">
                    <wxc-button text="确认"
                        size="full"
                        :btnStyle="btnStyle"
                        textStyle="{color:'#ffffff'}"
                        @wxcButtonClicked="checkConfirm()"></wxc-button>
                </div>
            </div>
        </scroller>
        <wxc-popup width="500"
                 :show="showContentPop"
                 @wxcPopupOverlayClicked="popClose"
                 pos="right">
            <scroller class="container" :style="scrollerStyle">
                <div>
                    <wxc-cell :cell-style="cellStyle">
                        <text slot="title" style="color:#f49428">{{showContent.name}}</text>
                    </wxc-cell>

                    <wxc-cell title="保养内容:" :cell-style="cellStyle" :desc="showContent.content">
                    </wxc-cell>

                    <wxc-cell title="保养要求" :cell-style="cellStyle" :desc="showContent.standard">
                    </wxc-cell>

                    <wxc-cell :cell-style="cellStyle">
                        <text slot="title">检查结论</text>
                        <bui-radio style="margin-right:250" 
                                    slot="value" 
                                    v-model="showContent.result" 
                                    :items="resultList" 
                                    selectedColor="#f49428"
                                    @change="changeResult">
                        </bui-radio>
                    </wxc-cell>

                    <wxc-cell :cell-style="cellStyle" v-if="showContent.mustPhotos === 1">
                        <text style="margin-right:80" slot="label">上传照片</text>
                        <div slot="value" class="img-div" @click="pickImg('heyPath')">
                            <image v-if="showContent.photo" class="image-upload" :src="showContent.photo"></image>
                            <text v-if="!showContent.photo" class="text">上传照片</text>
                        </div>
                    </wxc-cell>
                    
                    <wxc-cell :has-bottom-border="false" :cell-style="cellStyle">
                        <text style="margin-right:80" slot="label">填写备注</text>
                        <textarea class="textArea" slot="title" rows="5" @change="changeRemark" :value="showContent.remark"></textarea>
                    </wxc-cell>
                    
                </div>
            </scroller>
        </wxc-popup>
        <wxc-loading :show="showLoading" :need-mask="mask"></wxc-loading>
    </div>
</template>
<script>
import menu from '../common/menu'
import util from '../utils/util';
import {buiRadio} from 'bui-weex'
import { WxcCell,WxcLoading,Utils,WxcPopup,WxcButton } from 'weex-ui';
import { log } from 'util';
var waterMasker = weex.requireModule('waterMasker')
var uploadOss = weex.requireModule('uploadOss')
var amap = weex.requireModule('amap')
var axios = weex.requireModule('bmAxios')
var utilModule = weex.requireModule('UtilModule')
export default {
    components: {
        buiRadio,
        Utils,
        WxcCell,
        WxcLoading,
        WxcPopup,
        WxcButton,
        menu
    },
    created() {
        
    },
    data() {
        return {
            token:'',
            upkeepId:'',
            upkeepTypeId:'',
            data:{},
            upkeepCentList: [],
            resultList:[
                {value:'正常',title:'正常'},
                {value:'无此项',title:'无此项'},
                {value:'需修理',title:'需修理'},
            ],
            filter:{},
            valueStyle:{
                color:'rgb(153, 153, 153)',
            },
            barStyle:{
                backgroundColor:'#f49428',
            },
            cellStyle:{
                
            },
            btnStyle:{
                backgroundColor:'#f49428',
                borderColor: '#f49428'
            },
            showLoading:false,
            mask:true,
            showMenu:false,
            refreshing: false,
            showRefresh:false,
            leftItem: {
                text: '菜单',
            },
            showContent: {
                id: '',
                name: '',
                standard: '',
                remark: '',
                // selected: false,
                photo: ''
            },
            showContentPop: false,
            address:'',
            statusHeight: Number.parseInt(this.statusBarHeight || weex.config.env.statusBarHeight || 40)
        }
    },
    methods: {
        onrefresh(){
            this.refreshing = true
            this.listUpkeepCent()
        },
        listUpkeepCent(){
            this.showLoading = true
            let filter = {}
            filter.upkeepId = this.upkeepId
            filter.typeId = this.upkeepTypeId
            this.$fetch({
                header:{
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': `Bearer `+ this.token
                },
                method: 'POST',    
                name: 'listUpkeepCent',
                data: filter
            }).then(res => {
                if(res.success){
                    this.upkeepCentList = res.data.map(function (item) {
                        return {
                            id: item.id,
                            name: item.name,
                            standard: item.standard,
                            content: item.content,
                            remark: item.remark ? item.remark : '',
                            mustPhotos: item.mustPhotos,
                            // selected: false,
                            photo: item.photo ? item.photo : '',
                            result: item.result ? item.result : '正常'
                        }
                    })
                    this.$storage.set('upkeepCentList_'+this.upkeepTypeId+"_"+this.upkeepId, JSON.stringify(this.upkeepCentList))

                }else{
                    this.$notice.toast({
                        message: '网络错误'
                    })
                }
            }, error => {
                this.$notice.toast({
                    message: '网络错误'
                })
            })
            this.showLoading = false
            setTimeout(() => {
                this.refreshing = false
            }, 500)
        },
        checkButton(number){
            this.showContentPop = !this.showContentPop
            this.upkeepCentList = this.upkeepCentList.map((item, index) => {
                if (number === index) {
                this.showContent = {
                    id: item.id,
                    name: item.name,
                    content: item.content,
                    standard: item.standard,
                    remark: item.remark,
                    // selected: !item.selected,
                    mustPhotos: item.mustPhotos,
                    photo: item.photo,
                    result: item.result
                }
                return {
                    id: item.id,
                    name: item.name,
                    content: item.content,
                    standard: item.standard,
                    remark: item.remark,
                    // selected: !item.selected,
                    mustPhotos: item.mustPhotos,
                    photo: item.photo,
                    result: item.result
                }
                } else {
                return item
                    }
                })
        },
        changeResult (result) {
            this.upkeepCentList = this.upkeepCentList.map((item, index) => {
                if (this.showContent.id === item.id) {
                this.showContent = {
                    id: item.id,
                    name: item.name,
                    content: item.content,
                    standard: item.standard,
                    remark: item.remark,
                    // selected: item.selected,
                    mustPhotos: item.mustPhotos,
                    photo: item.photo,
                    result: result
                }
                return {
                    id: item.id,
                    name: item.name,
                    content: item.content,
                    standard: item.standard,
                    remark: item.remark,
                    // selected: item.selected,
                    mustPhotos: item.mustPhotos,
                    photo: item.photo,
                    result: result
                }
                } else {
                return item
                }
            })
        },
        changeRemark(event){
            this.upkeepCentList = this.upkeepCentList.map((item, index) => {
                if (this.showContent.id === item.id) {
                    return {
                        id: item.id,
                        name: item.name,
                        content: item.content,
                        standard: item.standard,
                        remark: event.value,
                        // selected: item.selected,
                        mustPhotos: item.mustPhotos,
                        photo: item.photo,
                        result: item.result
                    }
                    } else {
                    return item
            }   
        })
            
        },
        pickImg(typeId){
            if(this.address == ''){
                this.$notice.toast({
                    message: '无定位信息，请重新返回并重新打开此页面'
                })
                return
            }
            this.$image.camera({
                maxCount: 1
            })
            .then(resData => {
                this.$notice.loading.show()
                var imgSor = resData[0]
                var name =  typeId + '_'+ this.data.upkeepNumber + '_' + Date.parse(new Date()) +'.png'
                //水印内容
                var staffName = this.data.staff1Name
                var time = new Date().toLocaleString()
                var text = staffName + '  ' + this.address + '  ' + time
                this.getWaterMask(imgSor,name,text,typeId)
            }, error => {
            })
            
        },
        getWaterMask(imgSor,name,text,typeId){
            var _this = this
            waterMasker.transform(imgSor,name,text,
            function(resData){
                var imgPath = resData.imgPath + '/' + name
                let date = new Date()
                let objName = 'staff/' + 'credentials' + '/' 
                            + _this.data.upkeepNumber 
                            + '_' + date.getFullYear() + (date.getMonth() + 1) 
                            + date.getDate() + date.getHours() 
                            + date.getMinutes() 
                            + date.getSeconds() 
                            + date.getMilliseconds() + typeId + '.png' 
                _this.uploadOss(imgPath,objName)
            })
        },
        uploadOss(path,objName){
            let _this = this
            uploadOss.upload(path,objName,function(resData){
                if(resData.result == 'success'){
                    _this.getImg(resData.url)
                    _this.$notice.loading.hide()
                }else{
                    _this.$notice.toast({
                        message: '上传失败，请检查网络'
                    })
                    _this.$notice.loading.hide()
                }
            })
        },
        getImg (imgPath) {
            this.upkeepCentList = this.upkeepCentList.map((item, index) => {
                if (this.showContent.id === item.id) {
                this.showContent = {
                    id: item.id,
                    name: item.name,
                    content: item.content,
                    standard: item.standard,
                    remark: item.remark,
                    // selected: item.selected,
                    mustPhotos: item.mustPhotos,
                    photo: imgPath,
                    result: item.result
                }
                return {
                    id: item.id,
                    name: item.name,
                    content: item.content,
                    standard: item.standard,
                    remark: item.remark,
                    // selected: item.selected,
                    mustPhotos: item.mustPhotos,
                    photo: imgPath,
                    result: item.result
                }
                } else {
                return item
                }
            })
        },
        popClose(){
            this.showContentPop = false
        },
        checkConfirm () {
            let _this = this
            this.$notice.confirm({
                title: '提示',
                message: '您已核对过所有维保项目吗?',
                okTitle: '确认',
                cancelTitle: '取消',
                okCallback() {
                    
                    for (const i in _this.upkeepCentList) {
                        if (_this.upkeepCentList[i].mustPhotos === 1) {
                            if (!_this.upkeepCentList[i].photo) {
                                _this.$notice.toast({
                                    message: `保养项目${parseInt(i) + 1}照片未上传!`
                                })
                                return
                            }
                        }
                    }
                    _this.handleConfirm()
                },
                cancelCallback() {
                    return
                }
            })
        },
        handleConfirm(){
            //保存保养项目
            this.showLoading = true
            let filter = {}
            filter.upkeepId = this.data.upkeepId
            // filter.endLocation = address
            filter.list = this.upkeepCentList.map((item) => {
                return {
                    upkeepId: this.data.upkeepId,
                    upkeepCentId: item.id,
                    remark: item.remark,
                    photo: item.photo,
                    result: item.result
                }
            })
            this.$fetch({
                header:{
                    'Content-type': 'application/json',
                    'Authorization': `Bearer `+ this.token
                },
                method: 'POST',    
                name: 'saveUpkeepCent',
                data: filter,
            }).then(res => {
                if(res.success){
                    this.showLoading = false
                    //跳转签字确认页

                    // this.$router.toWebView({
                    //     url: 'http://www.baidu.com',
                    //     title: '签字确认',
                    //     navShow: true
                    // })
                    // this.$router.open({
                    //     name: 'signature',
                    //     params:{upkeepDetail:this.data}
                    // })
                    // let src = `https://zn.hyjtyl.com/wxGov/wechat.html#/appSignature?upkeepId=${this.data.upkeepId}&upkeepNumber=${this.data.upkeepNumber}`
                    let src = `http://test.hyjtyl.com/wechat.html#/appSignature?upkeepId=${this.data.upkeepId}&upkeepNumber=${this.data.upkeepNumber}`
                    this.$router.toWebView({
                        url: src,
                        title: '签字确认',
                        navShow: true 
                    })
                    
                }else{
                    this.$notice.toast({
                        message: '您的网络不给力，已保存到本地'
                    })
                    this.showLoading = false
                }
            }, error => {
                this.$notice.toast({
                    message: '您的网络不给力，已保存到本地'
                })
                this.showLoading = false
            })
            this.$storage.set('upkeepCentList_'+this.upkeepTypeId, JSON.stringify(this.upkeepCentList))
        },
        getAddress(locationLng,locationLat){
            let data = {}
            let _this = this
            let loc = locationLng+','+locationLat
            data.location = loc
            data.key = 'c1f73016285c30b57fda31598f5757c2'
            this.$fetch({
                method: 'GET',
                url: 'https://restapi.amap.com/v3/geocode/regeo',
                header: {},
                data: data,
                timeout: 3000
            }).then(resData => {
                if(resData.status == "1"){
                    this.address = resData.regeocode.formatted_address
                }else{
                    this.getLocationFromStorage()
                }
            }, error => {
                this.getLocationFromStorage()
            })
        },
        getDetail(){
            let filter = {}
            filter.upkeepId = this.data.upkeepId
            this.$fetch({
                header:{
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': `Bearer `+ this.token
                },
                method: 'POST',    
                name: 'getUpkeepDetail',
                data: filter
            }).then(resData => {
                if(resData.success){
                   if(resData.data.status == 2){
                       this.$router.back({
                            length: 2,
                            type: 'PUSH'
                        })
                   }
                }else{
                    this.$notice.toast({
                        message: '网络错误'
                    })
                }
            }, error => {

            })
        },
        getLocationFromStorage(){
            let _this = this
            this.$storage.get('address').then(resData => {
                this.$notice.confirm({
                    title: '定位失败',
                    message: '是否使用此地址:'+resData ,
                    okTitle: '确认',
                    cancelTitle: '取消',
                okCallback() {
                    _this.address = resData
                },
                cancelCallback() {
                    // 点击取消按钮的回调
                }
            })
            },error => {

            })
        }
    },
    created(){
        this.$notice.loading.show()
        const tabPageHeight = Utils.env.getPageHeight()
        const containerHeight = tabPageHeight
        this.scrollerStyle ={ height: containerHeight + 'px' }
         if(Utils.env.isAndroid()){
            this.refreshStyle = {marginTop:'-90px'}
        }
        //获取token
        this.token = this.$storage.getSync('token')
        if(!this.token){
            this.$router.setHomePage('/pages/login.js')
        }

        this.$router.getParams().then(resData => {
            this.data = resData.upkeepDetail
            this.upkeepId = this.data.upkeepId
            this.upkeepTypeId = this.data.upkeepTypeId
            // 获取缓存数据
            this.$storage.get('upkeepCentList_'+this.upkeepTypeId+"_"+this.upkeepId).then(resData => {
                this.upkeepCentList = JSON.parse(resData);
            },error => {
                this.listUpkeepCent()
            })
            // this.upkeepCentList = JSON.parse(this.$storage.getSync('upkeepCentList_'+ this.upkeepTypeId))
           
        })
        
        //获取定位
        this.$geo.get().then(data => {
            //获取行政位置
            var locationLng = data.locationLng
            var locationLat = data.locationLat
            // var locationLng = '120.246842'
            // var locationLat = '31.546071'
            this.getAddress(locationLng,locationLat)
        }, error => {
            this.getLocationFromStorage()
        })
        this.$notice.loading.hide() 
    },
    eros:{
        beforeBackAppear(){
            this.$notice.loading.show()
            this.getDetail()
            this.$notice.loading.hide()
            
        }
    }
    
}
</script>
<style scoped>
.status-bar{
    background-color:#f49428;
}
.staffList {
    width: 750px;
    background-color: #f2f3f4;
}
.image {
    width: 40px;
    height: 40px;
    margin-right: 20px;
}
.locationImg{
    width: 50px;
    height: 50px;
}
.container {
    flex: 1;
    width: 750px;
    background-color: #f2f3f4;
}
.refresh {
    width: 750px;
    height: 100px;
    display: -ms-flex;
    display: -webkit-flex;
    display: flex;
    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;
    align-items: center;
}
.indicator {
    /* margin-top: 16px; */
    height: 80px;
    width: 80px;
    color: #f49428;
}
.list{
    margin-top: 10px;
    margin-left: 20px;
    margin-right: 20px;
}
.text-no{
  text-align: center;
  margin-top: 100;
  font-size: 35;
  color: #999999
}
.img-div{
    height: 250 ;
    width: 250;
    background-color: #e2e2e2;
    justify-content: center;
    align-items: center;
    margin-right: 250px;
}
.image-upload{
    width: 250;
    height: 250;
}
.textArea{
    background-color: #e2e2e2;
    color:#999999;
    margin-right: 250px;
    height: 250;
}
.text{
    color: #999999;
    font-size: 35;
}
.div-button{
    flex-direction: row;
    justify-content: space-around;
    margin-bottom: 10px;
}  
</style>

